package com.qqbot.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @PackageName : com.eezi.app.schedule
 * @Author : wenwu.cai
 * @Date : 2022/3/30 11:10 上午
 * @Description : TODO
 **/
@Slf4j
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Value("${schedule.corePoolSize:12}")
    private Integer corePoolSize;

    @Value("${schedule.maxPoolSize:14}")
    private Integer maxPoolSize;

    @Value("${schedule.queueCapacity:10}")
    private Integer queueCapacity;

    @Value("${schedule.awaitTime:60}")
    private Integer awaitTime;

    @Value("${schedule.keepAlive:60}")
    private Integer keepAlive;

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程池数量
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程池数量
        executor.setMaxPoolSize(maxPoolSize);
        //线程池所使用的缓冲队列
        executor.setQueueCapacity(queueCapacity);
        //等待时间（默认为0，此时立即停止），并没等待xx秒后强制停止
        executor.setAwaitTerminationSeconds(awaitTime);
        //空闲线程存活时间
        executor.setKeepAliveSeconds(keepAlive);
        //线程池名称前缀
        executor.setThreadNamePrefix("thread-pool-");
        //线程池拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
                log.error("自定义多线程异步线程异常处理：{}.{}；message：{}", method.getDeclaringClass(), method.getName(), throwable.getMessage());
            }
        };
    }
}
